<template></template>
<script setup lang="ts" name="WorkflowVariableBlock">

import {
  $insertNodes,
  COMMAND_PRIORITY_EDITOR,
} from 'lexical'
import { mergeRegister } from '@lexical/utils'
import { useLexicalComposer} from 'lexical-vue'
import {
  $createWorkflowVariableBlockNode,
  WorkflowVariableBlockNode,
} from './node'
import { onMounted, onUnmounted } from 'vue'
import {INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND,DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND,CLEAR_HIDE_MENU_TIMEOUT
 , Var
} from '../types'



export type WorkflowVariableBlockProps = {
}

  const editor = useLexicalComposer()
  let unregisterListener: () => void
  onMounted(() => {
    if (!editor.hasNodes([WorkflowVariableBlockNode]))
      throw new Error('WorkflowVariableBlockPlugin: WorkflowVariableBlock not registered on editor')

    unregisterListener =  mergeRegister(
      editor.registerCommand(
        INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND,
        (v:Var) => {
          editor.dispatchCommand(CLEAR_HIDE_MENU_TIMEOUT, undefined)
          const workflowVariableBlockNode = $createWorkflowVariableBlockNode(v.varName,v.group)
          $insertNodes([workflowVariableBlockNode])
          return true
        },
        COMMAND_PRIORITY_EDITOR,
      ),
      editor.registerCommand(
        DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND,
        () => {
          return true
        },
        COMMAND_PRIORITY_EDITOR,
      ),
    )
  })

   onUnmounted(()=> {
    unregisterListener();
   })

</script>

